<template>
  <q-dialog v-model="show" @hide="handleClose">
    <q-card class="add-contact-dialog">
      <q-card-section class="dialog-header">
        <div class="dialog-title">{{ title || '选择要添加的联系人' }}</div>
        <div class="dialog-subtitle">{{ subtitle || '选择要添加到群组中的联系人' }}</div>
        <q-btn 
          icon="close" 
          flat 
          round 
          dense 
          class="close-btn"
          @click="handleClose"
        />
      </q-card-section>

      <q-card-section class="dialog-body">
        <q-input
          v-model="searchQuery"
          placeholder="搜索好友"
          outlined
          dense
          class="search-input"
          autocomplete="off"
          clearable
        >
          <template v-slot:prepend>
            <q-icon name="search" size="18px" />
          </template>
        </q-input>

        <div v-if="filteredFriends.length === 0" class="empty-state">
          <q-icon name="people_outline" size="64px" color="grey-4" />
          <div class="empty-text">
            {{ friends.length === 0 ? '暂无好友可添加' : '未找到匹配的好友' }}
          </div>
        </div>

        <q-list v-else class="friends-list" separator>
          <q-item
            v-for="friend in filteredFriends"
            :key="friend.id"
            clickable
            v-ripple
            class="friend-item"
            :class="{ 'friend-item-selected': selectedFriendId === friend.id }"
            @click="selectFriend(friend.id)"
          >
            <q-item-section avatar>
              <q-avatar size="48px" class="friend-avatar">
                <img 
                  v-if="getAvatarUrl(friend)" 
                  :src="getAvatarUrl(friend)!" 
                  @error="handleAvatarError($event, friend)"
                />
                <div
                  v-else
                  class="avatar-placeholder"
                  :style="getAvatarStyle(friend.id)"
                >
                  {{ friend.name?.[0]?.toUpperCase() || 'U' }}
                </div>
              </q-avatar>
            </q-item-section>
            
            <q-item-section>
              <q-item-label class="friend-name">{{ friend.name }}</q-item-label>
              <q-item-label 
                v-if="friend.remark && friend.remark !== friend.name" 
                caption 
                class="friend-remark"
              >
                {{ friend.remark }}
              </q-item-label>
            </q-item-section>
            
            <q-item-section side>
              <q-radio
                :model-value="selectedFriendId"
                :val="friend.id"
                @update:model-value="selectFriend"
                color="primary"
              />
            </q-item-section>
          </q-item>
        </q-list>
      </q-card-section>

      <q-card-actions align="right" class="dialog-actions">
        <q-btn
          flat
          label="取消"
          color="grey-7"
          @click="handleClose"
          class="cancel-btn"
          no-caps
        />
        <q-btn
          unelevated
          label="确定"
          color="primary"
          :disable="!selectedFriendId"
          @click="handleConfirm"
          class="confirm-btn"
          no-caps
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { getAvatarStyle } from '@/utils/avatar'
import { API_BASE_URL } from '@/config/env'
import { getCachedImageUrl } from '@/services/image-cache'

export interface Friend {
  id: string
  name: string
  remark?: string
  avatar?: string
  file_name?: string
}

const props = defineProps<{
  modelValue: boolean
  friends: Friend[]
  title?: string
  subtitle?: string
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [friendId: string]
}>()

const show = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const searchQuery = ref('')
const selectedFriendId = ref<string | null>(null)
const cachedAvatarUrls = ref<Record<string, string>>({})
const avatarErrors = ref<Record<string, boolean>>({})

const filteredFriends = computed(() => {
  if (!searchQuery.value.trim()) {
    return props.friends
  }
  const query = searchQuery.value.toLowerCase().trim()
  return props.friends.filter(f => 
    f.name.toLowerCase().includes(query) ||
    (f.remark && f.remark.toLowerCase().includes(query))
  )
})

const selectFriend = (friendId: string) => {
  selectedFriendId.value = friendId
}

const handleConfirm = () => {
  if (selectedFriendId.value) {
    emit('confirm', selectedFriendId.value)
    handleClose()
  }
}

const handleClose = () => {
  show.value = false
  searchQuery.value = ''
  selectedFriendId.value = null
}

const handleAvatarError = (event: Event, friend: Friend) => {
  avatarErrors.value[friend.id] = true
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

// 获取头像URL
const getAvatarUrl = (friend: Friend): string | null => {
  if (avatarErrors.value[friend.id]) {
    return null
  }
  
  if (cachedAvatarUrls.value[friend.id]) {
    return cachedAvatarUrls.value[friend.id]
  }
  
  if (friend.avatar) {
    return friend.avatar
  }
  
  if (friend.file_name) {
    return `${API_BASE_URL}/api/upload/${friend.file_name}`
  }
  
  return null
}

// 加载好友头像
const loadFriendAvatar = async (friend: Friend) => {
  if (avatarErrors.value[friend.id] || cachedAvatarUrls.value[friend.id]) {
    return
  }
  
  const url = getAvatarUrl(friend)
  if (!url || url.startsWith('data:')) {
    return
  }
  
  try {
    const cachedUrl = await getCachedImageUrl(url, true)
    if (cachedUrl) {
      cachedAvatarUrls.value[friend.id] = cachedUrl
    } else {
      avatarErrors.value[friend.id] = true
    }
  } catch (error) {
    console.warn(`加载好友 ${friend.id} 的头像失败:`, error)
    avatarErrors.value[friend.id] = true
  }
}

// 监听好友列表变化，加载头像
watch(() => props.friends, async (newFriends) => {
  for (const friend of newFriends) {
    if (getAvatarUrl(friend) && !cachedAvatarUrls.value[friend.id] && !avatarErrors.value[friend.id]) {
      await loadFriendAvatar(friend)
    }
  }
}, { immediate: true, deep: true })

watch(() => props.modelValue, (val) => {
  if (val) {
    selectedFriendId.value = null
    searchQuery.value = ''
    // 重置头像缓存和错误状态（可选，如果需要每次都重新加载）
    // cachedAvatarUrls.value = {}
    // avatarErrors.value = {}
  }
})
</script>

<style lang="sass" scoped>
.add-contact-dialog
  min-width: 480px
  max-width: 560px
  width: 100%
  border-radius: 12px
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif
  -webkit-font-smoothing: antialiased
  -moz-osx-font-smoothing: grayscale
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12)

.dialog-header
  padding: 24px 24px 16px
  position: relative
  border-bottom: 1px solid rgba(0, 0, 0, 0.06)

  .dialog-title
    font-size: 18px
    font-weight: 600
    letter-spacing: -0.01em
    color: #1a1a1a
    line-height: 1.4
    margin-bottom: 4px

  .dialog-subtitle
    font-size: 13px
    font-weight: 400
    letter-spacing: 0.01em
    color: #718096
    line-height: 1.5

  .close-btn
    position: absolute
    top: 20px
    right: 16px
    color: #718096

    &:hover
      background: rgba(0, 0, 0, 0.04)

.dialog-body
  padding: 20px 24px
  max-height: 480px
  overflow-y: auto
  
  // 自定义滚动条样式
  &::-webkit-scrollbar
    width: 6px
  
  &::-webkit-scrollbar-track
    background: transparent
  
  &::-webkit-scrollbar-thumb
    background: rgba(0, 0, 0, 0.2)
    border-radius: 3px
    
    &:hover
      background: rgba(0, 0, 0, 0.3)

  .search-input
    margin-bottom: 16px

    :deep(.q-field__control)
      height: 40px

    :deep(.q-field__native)
      font-size: 14px
      letter-spacing: 0.01em
      color: #1a1a1a

    :deep(.q-field__label)
      font-size: 14px
      color: #718096

  .empty-state
    display: flex
    flex-direction: column
    align-items: center
    justify-content: center
    padding: 80px 24px
    color: #a0aec0

    .empty-text
      margin-top: 20px
      font-size: 14px
      font-weight: 400
      letter-spacing: 0.01em
      color: #718096
      text-align: center

  .friends-list
    // 移除重复的 max-height，因为父容器已经设置了
    
    .friend-item
      padding: 14px 16px
      transition: all 0.2s ease
      border-radius: 8px
      margin: 2px 0
      min-height: 64px

      &:hover
        background: rgba(0, 0, 0, 0.04)
        transform: translateX(2px)

      &.friend-item-selected
        background: rgba(25, 118, 210, 0.12)
        border-left: 3px solid #1976d2

      .friend-avatar
        .avatar-placeholder
          width: 100%
          height: 100%
          display: flex
          align-items: center
          justify-content: center
          color: white
          font-size: 18px
          font-weight: 500
          letter-spacing: 0
          -webkit-font-smoothing: antialiased
          -moz-osx-font-smoothing: grayscale

      .friend-name
        font-size: 15px
        font-weight: 500
        letter-spacing: 0.01em
        color: #1a1a1a
        line-height: 1.4

      .friend-remark
        font-size: 13px
        font-weight: 400
        letter-spacing: 0.01em
        color: #718096
        line-height: 1.4
        margin-top: 2px

.dialog-actions
  padding: 12px 24px 20px
  border-top: 1px solid rgba(0, 0, 0, 0.06)

  .cancel-btn, .confirm-btn
    min-width: 88px
    height: 40px
    font-size: 15px
    font-weight: 500
    letter-spacing: 0.02em
    border-radius: 8px
    -webkit-font-smoothing: antialiased
    -moz-osx-font-smoothing: grayscale

  .cancel-btn
    margin-right: 12px

  .confirm-btn
    padding: 0 24px
    
    &:disabled
      opacity: 0.5
</style>

